using System;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;

class InputCodeGenerator
{
     [MenuItem("Tools/Generate Code from InputActions")]
    public static void GenerateCodeFromInputActions()
    {
        // 找到 PlayerInputActions 的 InputActionAsset
        var playerInputActions = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/Settings/Input/PlayerInputActions.inputactions");
        if (playerInputActions == null)
        {
            Debug.LogError("PlayerInputActions.inputactions not found!");
            return;
        }

        StringBuilder codeBuilder = new StringBuilder();
        codeBuilder.AppendLine("using UnityEngine;");
        codeBuilder.AppendLine("using UnityEngine.InputSystem;");
        codeBuilder.AppendLine();
        codeBuilder.AppendLine("public partial class Player");
        codeBuilder.AppendLine("{");
        // codeBuilder.AppendLine("    private PlayerInput playerInput;");
        codeBuilder.AppendLine();

        // 生成字段和初始化代码
        foreach (var map in playerInputActions.actionMaps)
        {
            foreach (var action in map.actions)
            {
                string actionName = char.ToLower(action.name[0]) + action.name.Substring(1);
                codeBuilder.AppendLine($"    public InputAction {actionName}Action;");
                // codeBuilder.AppendLine($"    private void On{action.name}(InputAction.CallbackContext context) {{ \n }}");
            }
        }

        codeBuilder.AppendLine();
        codeBuilder.AppendLine("    private void InitActions()");
        codeBuilder.AppendLine("    {");
        // codeBuilder.AppendLine("        playerInput = GetComponent<PlayerInput>();");
        
        // 生成动作绑定代码
        foreach (var map in playerInputActions.actionMaps)
        {
            foreach (var action in map.actions)
            {
                string actionName = char.ToLower(action.name[0]) + action.name.Substring(1);
                codeBuilder.AppendLine($"        {actionName}Action = playerInput.actions[\"{action.name}\"];");
                // codeBuilder.AppendLine($"        {actionName}Action.performed += On{action.name};");
            }
        }

        codeBuilder.AppendLine("    }");
        codeBuilder.AppendLine("}");

        // 写入文件
        string path = "Assets/Scripts/Player/BasePlayerInput.cs";
        File.WriteAllText(path, codeBuilder.ToString());
        AssetDatabase.Refresh();

        Debug.Log("PlayerController.cs generated successfully.");
    }
}
